/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.chain;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import tal.drivechain.chain.script.ScriptCommand;

/**
 *
 * @author eisental
 */
public class FreePatcher extends Patcher{
    private List<ScriptCommand> conf;

    public void configure(List<ScriptCommand> configuration) throws IllegalArgumentException {
        conf = configuration;
    }

    public void patchNodes(Chain chain) throws IllegalArgumentException, AbortChainException {
        for (ScriptCommand command : conf)
            this.executePatchCommand(chain, command);
    }

    private List<ChainNode> getNodes(String outputs, Chain chain) throws AbortChainException {
        List<ChainNode> outs = new ArrayList<ChainNode>();
        outputs = outputs.trim();
        if (!outputs.startsWith("to "))
            throw new IllegalArgumentException("Bad syntax for connect command: connect [node-name] " + outputs);
        outputs = outputs.substring("to ".length());
        StringTokenizer tokenizer = new StringTokenizer(outputs, ",");
        while (tokenizer.hasMoreTokens()) {
            String name = tokenizer.nextToken().trim();
            ChainNode out = getNode(name, chain);
            outs.add(out);
        }
        return outs;
    }

    @Override
    public boolean isPatcherCommand(ScriptCommand command) {
        return (command.getName().equals("connect"));
    }

    @Override
    public void executePatchCommand(Chain chain, ScriptCommand command) throws IllegalArgumentException, AbortChainException {
        if (command.getName().equals("connect")) {
            ChainNode node = getNode(command.getArg1(), chain);
            if (node==null)
                throw new IllegalArgumentException("Can't find module " + command.getArg1());
            List<ChainNode> outs = getNodes(command.getArg2(), chain);
            for (ChainNode out : outs)
                node.addOutput(out);
        } else throw new IllegalArgumentException("Invalid script command name: " + command.getName());
    }

}
